package com.lagou.tdcqfdmeo.consume;

import com.lagou.rpcdemo.common.JSONSerializer;
import com.lagou.rpcdemo.common.RpcDecoder;
import com.lagou.rpcdemo.common.RpcEncoder;
import com.lagou.rpcdemo.request.RpcRequest;
import com.lagou.tdcqfdmeo.handler.UserClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class RpcConsumer {

    private static ExecutorService executorService = Executors.newFixedThreadPool(
            Runtime.getRuntime().availableProcessors()
    );

    private static UserClientHandler client;

    public static Object createProxy(final Class<?> serviceClass, final RpcRequest rpcRequest) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, (proxy, method, args) -> {
                    if (client == null) {
                        initClient();
                    }

                    rpcRequest.setMethodName(method.getName());
                    rpcRequest.setParameters(args);
                    rpcRequest.setClassName(serviceClass.getName());
                    rpcRequest.setParameterTypes(method.getParameterTypes());
                    client.setRequest(rpcRequest);

                    return executorService.submit(client).get();
                });
    }

    private static Class<?>[] convertTypeClass(Object[] args) {
        return Stream.of(args).map(Object::getClass).toArray(Class[]::new);
    }

    private static void initClient() {
        client = new UserClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(client);
                    }
                });

        try {
            bootstrap.connect("127.0.0.1", 8990).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
